<?php

namespace app\common\lib;

use app\common\cachemodel\name_analyze\Zl9NameAnalyzeCreateNameRecord;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeRecodeBack;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeRecodeCreateNameRecord;
use app\common\cachemodel\name_analyze\Zl9NameAnalyzeRecord;
use app\common\lib\horoscope\Horoscope;
use app\common\service\ChatParse;
use think\Log;
use think\queue\Job;

class NameAnalyzeJob
{
    /**
     * 名字评分
     * @param \think\queue\Job $job
     * @param $jobData
     * @return void
     */
    public function nameAnalyze(Job $job, $jobData)
    {
        // $jobData = [
        //     'id' => 1,  // 测试记录ID   app_acquired_astro_test_record表ID
        //     'force' => false,   // 是否强制重新计算  可不存在
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }
        $force = $jobData['force'] ?? false;
        $sTime = time();
        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "名字评分计算 开始:{$startTime} host:{$host} 名字评分记录ID:{$jobData['id']}";
        $zl9NameAnalyzeRecordModel = new Zl9NameAnalyzeRecord();
        try
        {
            $data = $zl9NameAnalyzeRecordModel->getInfoById($jobData['id']);
            if ($data['status'] === 2 && !$force)
            {
                $job->delete();
                return;
            }
            $recodeInfo = (new Zl9NameAnalyzeRecodeBack())->getInfoById($data['back_rid']);
            $baziData = Horoscope::getInstance([
                'recode' => $recodeInfo['recode_info'],
                'time_start' => 23,
                'time_type' => 0,
//            'advance' => [
//                'year' => date('Y', $timestamp) * 1,
//                'month' => date('m', $timestamp) * 1,
//                'day' => date('d', $timestamp) * 1,
//                'hour' => date('H', $timestamp) * 1,
//                'minute' => date('i', $timestamp) * 1,
//                'timezone' => 8,
//                'is_summer' => 0,
//            ]
            ])->getUserDataForAI();
            $createNamesData = (new Zl9NameAnalyzeRecodeCreateNameRecord())->getRecodeCreateNameData($data['rid']);
            $createNamesList = $createNamesData['create_names'] ?? [];
            $params = [
                'uid' => $data['uid'],
                'sur_name' => $data['surname'],   // 姓氏
                'name' => $data['name'], // 名字
                'calendar_date' => $data['content']['birth_time'],  // 出生日期
                'bazi' => $baziData['bazi'], // 八字，例如：年柱(乙亥) 月柱(癸水) 日柱(己酉) 时柱(庚午)
                'joyful_god' => $baziData['joyful_god'],    // 最大用神
                'pattern' => $baziData['pattern'],  //  格局，例如：['此处为内格局','此处为外格局']，如没有格局则为空字符串，如果包含多个用中文逗号拼接
                'chinese_calendar_date' => $baziData['chinese_calendar_date'],  //  农历日期例：乙亥年六月二十 午时
                'use_zhipu_ali_moonshot_type' => 3, //  使用模型类型 0=>智谱 1=>千问 2=>moonshot 3=>根据效果优先级处理顺序
                'is_create_name' => in_array($data['surname'] . $data['name'], $createNamesList) ? 1 : 0,
            ];
            $queryResult = ChatParse::getNameAnalyzeResultData($params);
            $content = $data['content'];
            if ($queryResult['success'] && isset($queryResult['data']['data']['code']) && $queryResult['data']['data']['code'] === 200)
            {
                //     'score' => '', // 分数
                //     'percentage' => '',  //  百分比
                //     'wx_score' => '',    //  五行分数
                //     'wx_analysis' => '', //  五行分析
                //     'ys_score' => '',    //  喜用神分数
                //     'ys_analysis' => '', //  喜用神分析
                //     'qh_score' => '',    //  整体契合分数
                //     'qh_analysis' => '', //  整体契合分析
                $queryResultData = $queryResult['data']['data'];
                $content['score'] = $queryResultData['title']['score'];
                $content['percentage'] = $queryResultData['title']['percentage'];
                $content['wx_score'] = $queryResultData['analysis']['five_elements']['score'];
                $content['ys_score'] = $queryResultData['analysis']['joyful_god']['score'];
                $content['ys_analysis'] = $queryResultData['analysis']['joyful_god']['analysis'];
                $content['qh_score'] = $queryResultData['analysis']['pattern']['score'];
                $content['qh_analysis'] = $queryResultData['analysis']['pattern']['analysis'];
                $status = 2;

                if (isset($data['order_num']) && $data['order_num'])
                {
                    (new \app\common\cachemodel\Orders())->UpdateData($data['order_num'], ['status' => 4, 'update_time' => time()], 4);
                }
            } else
            {
                $content['error'] = $queryResult;
                $status = 3;
            }
            $sucTime = time();
            //  更新信息
            $zl9NameAnalyzeRecordModel->UpdateData($jobData['id'], [
                'status' => $status,
                'content' => $content,
                'update_time' => $sucTime,
                'start_time' => $sTime,
                'success_time' => $sucTime,
            ]);
        }
        catch (\Exception $e)
        {
            Log::write('名字评分计算 NameAnalyzeJob model => nameAnalyze()异常;JobData:【' . json_encode($jobData, JSON_UNESCAPED_UNICODE) . '】错误消息：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');

            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);

        $job->delete();
    }

    /**
     * 八字起名
     * @param \think\queue\Job $job
     * @param $jobData
     * @return void
     */
    public function createName(Job $job, $jobData)
    {
        // $jobData = [
        //     'id' => 1,  // 测试记录ID   app_acquired_astro_test_record表ID
        //     'force' => false,   // 是否强制重新计算 可不存在
        // ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }
        $force = $jobData['force'] ?? false;
        $sTime = time();
        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "八字起名 计算 开始:{$startTime} host:{$host} 八字起名记录ID:{$jobData['id']}";
        $createNameRecordModel = new Zl9NameAnalyzeCreateNameRecord();
        try
        {
            $data = $createNameRecordModel->getInfoById($jobData['id']);
            if (!$data['status'])
            {   //  未解锁
                $job->delete();
                return;
            }
            if ($data['status'] === 2 && !$force)
            {   //  已计算成功
                $job->delete();
                return;
            }
            $content = $data['content'];
            $recodeBackModel = new Zl9NameAnalyzeRecodeBack();
            if ($data['type'] === 1)
            {   //  个人起名
                $recodeInfo = $recodeBackModel->getInfoById($data['params']['back_rid']);
                $baziData = Horoscope::getInstance([
                    'recode' => $recodeInfo['recode_info'],
                    'time_start' => 23,
                    'time_type' => 0,
                    // 'advance' => [
                    //     'year' => date('Y', $timestamp) * 1,
                    //     'month' => date('m', $timestamp) * 1,
                    //     'day' => date('d', $timestamp) * 1,
                    //     'hour' => date('H', $timestamp) * 1,
                    //     'minute' => date('i', $timestamp) * 1,
                    //     'timezone' => 8,
                    //     'is_summer' => 0,
                    // ],
                ])->getUserDataForAI();
                $num = (int)$data['params']['num'];
                $type = (int)$data['params']['type'];
                if ($num > 2 && $type > 0)
                {
                    if ($type === 1)
                    {   //  设置中位字
                        $fixedWord = $data['params']['text'];
                    } else
                    {   //  设置末尾字
                        $lastWord = $data['params']['text'];
                    }
                }
                $params = [
                    'uid' => $data['uid'],
                    'sur_name' => $data['params']['surname'],   // 姓氏
                    'sex_type' => (int)$data['params']['sex'] === 1 ? '男' : '女',   //  性别
                    'word_count' => $num, //  起名字数
                    'fixed_word' => $fixedWord ?? '', //  中位字（当word_count为2时，该参数不生效）
                    'last_word' => $lastWord ?? '',  //  末尾字（当word_count为2时，该参数不生效）
                    'calendar_date' => sprintf('%d年%02d月%02d日 %02d:%02d', $recodeInfo['recode_info']['year'], $recodeInfo['recode_info']['month'], $recodeInfo['recode_info']['day'], $recodeInfo['recode_info']['hour'], $recodeInfo['recode_info']['minute']),  // 出生日期
                    'individual_needs' => $data['params']['remark'],   //  用户个性化特殊要求
                    'bazi' => $baziData['bazi'], // 八字，例如：年柱(乙亥) 月柱(癸水) 日柱(己酉) 时柱(庚午)
                    'joyful_god' => $baziData['joyful_god'],    // 最大用神
                    'pattern' => $baziData['pattern'],  //  格局，例如：['此处为内格局','此处为外格局']，如没有格局则为空字符串，如果包含多个用中文逗号拼接
                    'chinese_calendar_date' => $baziData['chinese_calendar_date'],  //  农历日期例：乙亥年六月二十 午时
                    'use_zhipu_ali_moonshot_type' => 3, //  使用模型类型 0=>智谱 1=>千问 2=>moonshot 3=>根据效果优先级处理顺序
                ];
                $queryData = ChatParse::getCreateNameResultData(1, $params);
                if ($queryData['success'] && isset($queryData['data']['data']['code']) && $queryData['data']['data']['code'] === 200)
                {
                    $queryResultData = $queryData['data']['data'];
                    //  侧重用神起名 结果
                    $content['ys_name_result'] = $this->recommendNameResert($queryResultData['joyful_god_recommend']);
                    //  侧重格局起名 结果
                    $content['gj_name_result'] = $this->recommendNameResert($queryResultData['pattern_recommend']);
                    //  侧重特色要求起名 结果
                    $content['tsyq_name_result'] = $this->recommendNameResert($queryResultData['individual_recommend']);

                    $recommendName = array_merge($queryResultData['joyful_god_recommend']['recommend_name'] ?? [], $queryResultData['pattern_recommend']['recommend_name'] ?? [], $queryResultData['individual_recommend']['recommend_name'] ?? []);
                    (new Zl9NameAnalyzeRecodeCreateNameRecord())->SaveData($data['uid'], $data['params']['rid'], $recommendName);
                    $status = 2;
                } else
                {
                    $content['error'] = $queryData;
                    $status = 3;
                }
            } else
            {   //  公司起名
                $rids = array_column($data['params']['originator_data'], 'back_rid');
                $rids[] = $data['params']['back_company_rid'];
                $recodeList = $recodeBackModel->batchGetInfoByIds($rids);
                $founderRecord = [];
                foreach ($data['params']['originator_data'] as $originatorItem)
                {
                    $baziData = Horoscope::getInstance([
                        'recode' => $recodeList[$originatorItem['back_rid']]['recode_info'],
                        'time_start' => 23,
                        'time_type' => 0,
                    ])->getUserDataForAI();
                    $recodeItem = $recodeList[$originatorItem['back_rid']]['recode_info'];
                    $founderRecord[] = [
                        'name' => $originatorItem['name'],
                        'calendar_date' => sprintf('%d年%02d月%02d日 %02d:%02d', $recodeItem['year'], $recodeItem['month'], $recodeItem['day'], $recodeItem['hour'], $recodeItem['minute']),
                        'chinese_calendar_date' => $baziData['chinese_calendar_date'],
                        'bazi' => $baziData['bazi'],
                        'joyful_god' => $baziData['joyful_god'],
                        'pattern' => $baziData['pattern'],
                    ];
                }
                $companyRecodeInfo = $recodeList[$data['params']['back_company_rid']]['recode_info'];
                $companyBaziData = Horoscope::getInstance([
                    'recode' => $companyRecodeInfo,
                    'time_start' => 23,
                    'time_type' => 0,
                ])->getUserDataForAI();
                $params = [
                    'uid' => $data['uid'],
                    'founder_record' => $founderRecord,
                    'company_open_info' => [
                        'company_open_date' => sprintf('%d年%02d月%02d日 %02d:%02d', $companyRecodeInfo['year'], $companyRecodeInfo['month'], $companyRecodeInfo['day'], $companyRecodeInfo['hour'], $companyRecodeInfo['minute']),
                        'chinese_calendar_date' => $companyBaziData['chinese_calendar_date'],
                        'bazi' => $companyBaziData['bazi'],
                        'joyful_god' => $companyBaziData['joyful_god'],
                    ],
                    'city' => $companyRecodeInfo['birth_province'],
                    'business' => $data['params']['business'],
                    'individual_needs' => $data['params']['remark'],
                    'use_zhipu_ali_moonshot_type' => 3,
                ];
                $queryData = ChatParse::getCreateNameResultData(2, $params);
                if ($queryData['success'] && isset($queryData['data']['data']['code']) && $queryData['data']['data']['code'] === 200)
                {
                    $queryResultData = $queryData['data']['data'];
                    // 格局分析
                    $content['pattern'] = $queryResultData['pattern'];
                    // 喜用神分析
                    $content['joyful_god'] = $queryResultData['joyful_god'];
                    //  侧重 主营业务 起名结果
                    $content['business_recommend'] = $this->recommendNameResert2($queryResultData['business_recommend']);
                    //  侧重 特殊要求 起名结果
                    $content['individual_recommend'] = $this->recommendNameResert2($queryResultData['individual_recommend']);
                    //  整体分析
                    $content['summarize'] = $queryResultData['summarize'];

                    $status = 2;
                } else
                {
                    $content['error'] = $queryData;
                    $status = 3;
                }
            }
            if ($status === 2 && isset($data['order_num']) && $data['order_num'])
            {
                (new \app\common\cachemodel\Orders())->UpdateData($data['order_num'], ['status' => 4, 'update_time' => time()], 4);
            }
            $sucTime = time();
            $updateData = [
                'status' => $status,
                'content' => $content,
                'update_time' => $sucTime,
                'start_time' => $sTime,
                'success_time' => $sucTime,
            ];
            $createNameRecordModel->UpdateData($jobData['id'], $data['uid'], $updateData);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);

            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);

        $job->delete();
    }

    /**
     * 推荐名字 重组结果
     * @param array $data
     * @return array|null
     */
    private function recommendNameResert(array $data)
    {
        if (empty($data['recommend_name']))
        {
            return null;
        }
        $names = [];
        foreach ($data['recommend_name'] as $k1 => $nameItem)
        {
            $resNameArr = mb_str_split($nameItem);
            if ($k1 === 0)
            {
                $pinYin = $data['name_analysis']['first_name_pinyin'];
            } else
            {
                $pinYin = $data['name_analysis']['second_name_pinyin'];
            }
            $nameItemArr = [];
            foreach ($resNameArr as $k2 => $item)
            {
                $nameItemArr[] = [
                    'pinyin' => $pinYin[$k2],
                    'text' => $item,
                ];
            }
            $names[] = $nameItemArr;
        }
        return [
            'list' => [
                [
                    'names' => $names[0],
                    'desc' => $data['name_analysis']['first_name_analysis'],
                ], [
                    'names' => $names[1],
                    'desc' => $data['name_analysis']['second_name_analysis'],
                ],
            ],
            'desc' => $data['comp_analysis'] ?? '',   //  综合分析
        ];
    }

    /**
     * 推荐名字 重组结果
     * @param array $data
     * @return array|null
     */
    private function recommendNameResert2(array $data)
    {
        if (empty($data['recommend_name']))
        {
            return null;
        }
        $names = [];
        foreach ($data['recommend_name'] as $k1 => $nameItem)
        {
            $resNameArr = mb_str_split($nameItem);
            if ($k1 === 0)
            {
                $pinYin = $data['name_analysis']['first_name_pinyin'];
            } else
            {
                $pinYin = $data['name_analysis']['second_name_pinyin'];
            }
            $nameItemArr = [];
            foreach ($resNameArr as $k2 => $item)
            {
                $nameItemArr[] = [
                    'pinyin' => $pinYin[$k2],
                    'text' => $item,
                ];
            }
            $names[] = $nameItemArr;
        }
        return [
            [
                'names' => $names[0],
                'name_txt' => $data['recommend_name'][0],
                'content' => $data['name_analysis']['first_name_analysis'],
            ], [
                'names' => $names[1],
                'name_txt' => $data['recommend_name'][1],
                'content' => $data['name_analysis']['second_name_analysis'],
            ],
        ];
    }
}
